# coding=utf-8
from django import forms
from django.core.files.uploadedfile import UploadedFile
from com.kjssoft.rainbow import LOGGER

__author__ = 'Sea'

class ImageForm(forms.Form):

    IMAGE_FIELD_NAME                   = 'rainbow_image_file'
    IMAGE_UPLOADED_PROGRESS_FIELD_NAME = 'rainbow_image_progress'
    ACCEPT_IMAGE_TYPE                  = 'image/jpeg,image/png,image/gif,image/bmp'
    MAX_FILE_CONTENT_SIZE              = 1024 * 1024 * 1024

    ERROR_MESSAGES = {
        'notAllowedType':'',
        'overMaxFileSize':''
    }

    rainbow_image_file = forms.FileField(
        widget = forms.FileInput(attrs={
            'class':'rainbowImageSelector',
            'accept':ACCEPT_IMAGE_TYPE,
            'maxSize':MAX_FILE_CONTENT_SIZE,
            'multiple':"multiple",
        })
    )

    rainbow_image_progress = forms.CharField(
        widget = forms.HiddenInput,
        required = False
    )

    def _validate_image_type(self, image_type):
        return image_type and self.ACCEPT_IMAGE_TYPE.__contains__(image_type.lower())

    def _validate_image_size(self, image_size):
        return self.MAX_FILE_CONTENT_SIZE > image_size

    def clean_rainbow_image_file(self):
        img = self.cleaned_data.get(self.IMAGE_FIELD_NAME)
        LOGGER.debug('clean rainbow image file %s' % img)
        img = self.cleaned_data.get(self.IMAGE_FIELD_NAME)
        LOGGER.debug('clean rainbow image file %s' % img)
        if isinstance(img, UploadedFile):
            if not self._validate_image_type(img.content_type):
                raise forms.ValidationError(self.ERROR_MESSAGES.get('notAllowedType'))
            if not self._validate_image_size(img.size):
                raise forms.ValidationError(self.ERROR_MESSAGES.get('overMaxFileSize'))
        else:
            raise forms.ValidationError(self.ERROR_MESSAGES.get('notAllowedType'))
        return img
